package com.avecsys.quotemanager.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.jsf.FacesContextUtils;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.service.supplier.SupplierMasterService;
import com.avecsys.quotemanager.service.system.SystemUserService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.UIComponentUtils;
import com.avecsys.quotemanager.vo.SupplierVO;
import com.avecsys.quotemanager.vo.SystemUserVO;
import com.icesoft.faces.component.ext.HtmlInputHidden;

public class ValidatorSystemEmailRegisteredCheck extends BaseValidator
{
	private static final Log log = LogFactory.getLog(ValidatorSystemEmailRegisteredCheck.class);

	public FacesMessage validateFieldValue(FacesContext facesContext, UIComponent uIComponent,
			Object object) throws ValidatorException
	{
		String emailInputField = (String) object;
		SystemUserService systemUserService = (SystemUserService) FacesContextUtils.getWebApplicationContext(
				facesContext)
				.getBean("systemUserService");
		FacesMessage message = new FacesMessage();
		SystemUserVO systemUserVO = new SystemUserVO();
		HtmlInputHidden uiComponentSupplierId = (HtmlInputHidden) uIComponent.getParent().findComponent(
				"companyID");
		HtmlInputHidden uicomponentSupplierUserId = (HtmlInputHidden) uIComponent.getParent()
				.findComponent("systemUserID");
		if (!UIComponentUtils.isValueEmpty(uiComponentSupplierId))
		{
			systemUserVO.setCompanyId(new Long(uiComponentSupplierId.getValue().toString()));
		}
		if (!UIComponentUtils.isValueEmpty(uicomponentSupplierUserId))
		{
			systemUserVO.setSystemUserId(new Long(uicomponentSupplierUserId.getValue().toString()));
		}
		systemUserVO.setDefaultAdminUserEmail(emailInputField);
		try
		{
			if (!systemUserService.isSystemUserEmailNotRegistered(systemUserVO))
			{
				message.setSummary(MessageBoardUtil.getValue(
						facesContext,
							ApplicationConstants.RESOURCE_BUNDLE_SUPPLIER,
							ApplicationConstants.VALIDATOR_ERROR_SUPPLIER_EMAIL_REGISTERED_ALREADY,
							null));
			}
		}
		catch (BusinessException e)
		{
			log.error(e);
		}
		return message;
	}
}

